import { MiddlewareConsumer, Module, NestModule, RequestMethod,  } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import type { RedisClientOptions } from 'redis';
import { redisStore, RedisStore } from 'cache-manager-redis-store'
import { CacheModule, CacheModuleOptions, CacheStore } from '@nestjs/cache-manager';
import { AccessMiddleware } from '@/core/middlewares/access.middleware';
import { ProxyModule } from '@/modules/proxy/proxy.module';
import { EproxyModule } from '@/modules/eproxy/eproxy.module';
import { ClashModule } from './modules/clash/clash.module';
import { ScheduleModule } from './modules/schedule/schedule.module';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    CacheModule.registerAsync<RedisClientOptions>({
      isGlobal: true,
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async function(configService: ConfigService) {
        const store: RedisStore = await redisStore({
          url: configService.get("REDIS_URL"),
          ttl: 60 * 1000
        });
        return {
          store: store as unknown as CacheStore,
        }
      }
    }),
    ProxyModule,
    ClashModule,
    EproxyModule,
    ScheduleModule,
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(...[AccessMiddleware])
      .forRoutes({path: "*", method: RequestMethod.ALL})
  }
}
